-module(confirm_service).
-behaviour(gen_server).
-export([start/0,init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).
start() ->
	case gen_server:start({local, ?MODULE}, ?MODULE, [], []) of 
	{ok,_} ->
		ok;
	{error,Reason} ->
		io:format("start confirm service failure with ~p~n",[Reason])
	end.
init(_) ->
	error_logger:info_msg("confirm service is started~n"),
    {ok,[]}.
handle_call({send_sms,Mobile},_,S) ->
	lists:keydelete(Mobile,1,S),
	RN = integer_to_list(random:uniform(9999)),
	{reply,{ok,RN},[{Mobile,RN,calendar:local_time()}|S]};

handle_call({confirm,Mobile,Code},_,S) ->
	case lists:keyfind(Mobile,1,S) of
	{Mobile,Code,_} ->
		{reply, true , lists:keydelete(Mobile,1,S)};
	_ ->
		{reply,false, S}
	end;
handle_call(_,_,State) ->
	{reply, undefined, State}.	
handle_cast(_, State) ->
	{noreply,State}.
handle_info(_, State) ->
	{noreply,State}.
terminate(_, _) ->
	ok.
code_change(_, State, _) ->
	{ok,State}.
